package com.example.config.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.lang.util.ByteSource;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.HashSet;
import java.util.Set;

public class CustomRealm extends AuthorizingRealm {
    /**
     * 登录认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
            throws AuthenticationException {
        System.out.println("登录认证");
        // 用户输入的账号
        Object principal = authenticationToken.getPrincipal();
        // 根据输入的账号去查数据库
        // TODO
        // 这个方法的返回值会产生各种异常
        // null：UnknownAccountException
        // 账号或密码错误：IncorrectCredentialsException
        // 构造这个返回值需要账号去数据库中查询
        return new SimpleAuthenticationInfo(
                "admin", // 账号
                "2b0e37a1b02a8bb8aa80b718c7e5accf", // 数据库中的密码
                ByteSource.Util.bytes("7318221222661946"), // 数据库中的salt
                this.getName()
        );
    }

    /**
     * 请求授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("请求授权");
        System.out.println("账号：" + principalCollection.getPrimaryPrincipal());
        SimpleAuthorizationInfo authorizationInfo =
                new SimpleAuthorizationInfo();
        // TODO 根据用户名查数据库中的权限集合
        // authorizationInfo存入权限集合
        Set<String> permissions = new HashSet<>();
        permissions.add("1");
        permissions.add("2");
//        permissions.add("user:add");
        authorizationInfo.setStringPermissions(permissions);
        // 如果目标权限没有匹配项，就会抛AuthorizationException
        return authorizationInfo;
    }
}
